package com.wql.crypto;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import com.wql.crypto.common.HexUtils;

/**
 * 非对称加密算法，遵循私钥加密公钥解密
 * 
 * @author wuqinglong
 */
public class RSAUtils {
	private RSAUtils() {
	}

	private static final String KEY_ALGORITHM = "RSA";

	private static final String PUBLIC_KEY = "RSAPublicKey";

	private static final String PRIVATE_KEY = "RSAPrivateKey";

	private static final int KEY_SIZE = 512;

	private static final String CHARSET_NAME = "utf-8";

	/**
	 * 公钥加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 */
	public static String encryptByPublicKey(String data, String key) {
		try {
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(HexUtils.hexStr2byte(key));
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
			Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return HexUtils.byte2HexStr(cipher.doFinal(data.getBytes(CHARSET_NAME)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 公钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 */
	public static String decryptByPublicKey(String data, String key) {
		try {
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(HexUtils.hexStr2byte(key));
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
			Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			return new String(cipher.doFinal(HexUtils.hexStr2byte(data)), CHARSET_NAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 私钥加密
	 * 
	 * @param data
	 * @param key
	 */
	public static String encryptByPrivateKey(String data, String key) {
		try {
			PKCS8EncodedKeySpec pKeySpec = new PKCS8EncodedKeySpec(HexUtils.hexStr2byte(key));
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateKey = factory.generatePrivate(pKeySpec);
			Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			return HexUtils.byte2HexStr(cipher.doFinal(data.getBytes(CHARSET_NAME)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 私钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 */
	public static String decryptByPrivateKey(String data, String key) {
		try {
			PKCS8EncodedKeySpec pKeySpec = new PKCS8EncodedKeySpec(HexUtils.hexStr2byte(key));
			KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateKey = factory.generatePrivate(pKeySpec);
			Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return new String(cipher.doFinal(HexUtils.hexStr2byte(data)), CHARSET_NAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取公钥
	 * 
	 * @param map
	 * @return
	 */
	public static String getPublicKey(Map<String, Object> map) {
		return HexUtils.byte2HexStr(((Key) map.get(PUBLIC_KEY)).getEncoded());
	}

	/**
	 * 获取私钥
	 * 
	 * @param map
	 * @return
	 */
	public static String getPrivateKey(Map<String, Object> map) {
		return HexUtils.byte2HexStr(((Key) map.get(PRIVATE_KEY)).getEncoded());
	}

	/**
	 * 初始化密钥
	 * 
	 * @return
	 */
	public static Map<String, Object> initKey() {
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
			keyPairGen.initialize(KEY_SIZE);
			KeyPair keyPair = keyPairGen.generateKeyPair();
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(PUBLIC_KEY, publicKey);
			map.put(PRIVATE_KEY, privateKey);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String str = "hello world!";
		Map<String, Object> map = initKey();
		String pubKey = getPublicKey(map), priKey = getPrivateKey(map);
		System.out.println("str=" + str);
		System.out.println("pubKey=" + pubKey);
		System.out.println("priKey=" + priKey);
		System.out.println("----------------------------------------------------");
		System.out.println("priKey2Encrypto=" + encryptByPrivateKey(str, priKey));
		System.out.println("pubKey2Decrypto=" + decryptByPublicKey(encryptByPrivateKey(str, priKey), pubKey));
		System.out.println("----------------------------------------------------");
		System.out.println("pubKey2Encrypto=" + encryptByPublicKey(str, pubKey));
		System.out.println("priKey2Decrypto=" + decryptByPrivateKey(encryptByPublicKey(str, pubKey), priKey));

	}
}
